package com.eightywork.life.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.eightywork.life.R;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.umeng.analytics.MobclickAgent;

public class LoginActivity extends BaseActivity implements OnClickListener, Callback  {                      
	private EditText account, password;
	private ImageButton returnButton;
	private Button loginButton, rightButton, forgetButton, sina, tencent;
	private AsyncTask task;
	public static LoginActivity activity = null;
	private boolean failConnectToInternet;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_login);
		activity = this;
		failConnectToInternet = getIntent().getBooleanExtra("failConnectToInternet", false);
		if (failConnectToInternet) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("检测到你没有连接网络，请问是否打开网络继续登陆？");
			builder.setPositiveButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.setNegativeButton("确认",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
						}
					});
			builder.show();
		}
		initView();
		initData();
		ShareSDK.initSDK(context);
		
	}

	@Override
	protected void onDestroy() {
		if (task != null) {
			task.cancel(true);
		}
		super.onDestroy();
	}
	
	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}


	public void initView() {
		initHeader("登 录");
		account = (EditText) findViewById(R.id.account);
		password = (EditText) findViewById(R.id.password);
		returnButton = (ImageButton) findViewById(R.id.button_left);
		rightButton = (Button) findViewById(R.id.button_right);
		loginButton = (Button) findViewById(R.id.login);
		forgetButton = (Button) findViewById(R.id.button_forget);
		sina = (Button) findViewById(R.id.sina);
		tencent = (Button) findViewById(R.id.tencent);
		returnButton.setOnClickListener(this);
		loginButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		forgetButton.setOnClickListener(this);
		sina.setOnClickListener(this);
		tencent.setOnClickListener(this);
	}
	
	public void initData() {
		if (failConnectToInternet) {
			account.setText(CacheService.getAccount());
			password.setText(CacheService.getPassword());
		}
	}

	@Override
	public void onClick(View v) {
		if (v == returnButton) {
			hideKeyBoard(activity);
			finish();
		} else if (v == loginButton) {
			if(IndexActivity.activity != null) {
				IndexActivity.activity.finish();
			}
			login();
			hideKeyBoard(activity);
		} else if (v == rightButton) {
			Intent intent = new Intent(this, RegFirstActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		} else if (v == forgetButton) {
			Intent intent = new Intent(this, PasswordFirstActivity.class);
			startActivity(intent);
		} else if (v == sina) {
			final Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
			if (!weibo.isValid()) {
				 weibo.setPlatformActionListener(new PlatformActionListener() {

					public void onComplete(Platform plat, int action,
							HashMap<String, Object> res) {
						Message msg = new Message();
						msg.arg1 = 1;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, LoginActivity.this);
					}

					public void onError(Platform plat, int action, Throwable t) {
						t.printStackTrace();

						Message msg = new Message();
						msg.arg1 = 4;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, LoginActivity.this);
					}
					
					public void onCancel(Platform plat, int action) {
						Message msg = new Message();
						msg.arg1 = 3;
						msg.arg2 = action;
						msg.obj = plat;
						weibo.removeAccount();
						UIHandler.sendMessage(msg, LoginActivity.this);
					}
				});
				weibo.authorize();
			} else {
				task = new SinaLoginTask().execute();
			}
		} else if (v == tencent) {
			final Platform txWeibo = ShareSDK.getPlatform(context, TencentWeibo.NAME);
			if (!txWeibo.isValid()) {
				txWeibo.setPlatformActionListener(new PlatformActionListener() {

					public void onComplete(Platform plat, int action,
							HashMap<String, Object> res) {
						Message msg = new Message();
						msg.arg1 = 2;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, LoginActivity.this);
					}

					public void onError(Platform plat, int action, Throwable t) {
						t.printStackTrace();
					    txWeibo.removeAccount();
						Message msg = new Message();
						msg.arg1 = 4;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, LoginActivity.this);
					}
					
					public void onCancel(Platform plat, int action) {
						Message msg = new Message();
						msg.arg1 = 3;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, LoginActivity.this);
					}
				});
				txWeibo.authorize();
				
			} else {
				task = new TencentLoginTask().execute();
			}
		}
	}
	
	


	class SinaLoginTask extends AsyncTask<Void, String, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("登录中...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
				PlatformDb db = weibo.getDb();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				CacheService.save(DoService.loginByWeibo(db.get("nickname"),
						db.getUserId(), db.getToken(), sdf.format(new Date(db.getExpiresTime())),
						""));
				CacheService.saveProfile(CpService.profile());
				DataService.setStruMap(DoService.xiaoquStru());
				DataService.setGroupList(SpaceService.group());
				if (!DataService.isHavingTag()) {
					DataService.setTagList(SpaceService.tagList());
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				Intent intent = new Intent(context, IndexActivity.class);
			//	intent.putExtra("beginToload", true);
				startActivity(intent);			
				if (LoginMapActivity.activity != null) {
					LoginMapActivity.activity.finish();		
				}
				if (RegFirstActivity.activity != null) {
					RegFirstActivity.activity.finish();
				}
				if (RegSecondActivity.activity != null) {
					RegSecondActivity.activity.finish();
				}
				finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	class TencentLoginTask extends AsyncTask<Void, String, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("登录中...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Platform weibo = ShareSDK.getPlatform(context,
						TencentWeibo.NAME);
				PlatformDb db = weibo.getDb();
				CacheService.save(DoService.loginByQQ(db.get("nickname"),
						db.getUserId(), db.getToken(), ""));
				CacheService.saveProfile(CpService.profile());
				DataService.setStruMap(DoService.xiaoquStru());
				DataService.setGroupList(SpaceService.group());
				if (!DataService.isHavingTag()) {
					DataService.setTagList(SpaceService.tagList());
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				Intent intent = new Intent(context, IndexActivity.class);
				intent.putExtra("beginToload", true);
				startActivity(intent);
				if (LoginMapActivity.activity != null) {
					LoginMapActivity.activity.finish();		
				}
				if (RegFirstActivity.activity != null) {
					RegFirstActivity.activity.finish();
				}
				if (RegSecondActivity.activity != null) {
					RegSecondActivity.activity.finish();
				}
				finish();				
					
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	private void login() {
		task = new LoginTask().execute();
	}

	class LoginTask extends AsyncTask<Void, String, String> {
		String username, password1;

		@Override
		protected void onPreExecute() {
			username = account.getEditableText().toString();
			password1 = password.getEditableText().toString();
			showProgressDialog("登录中...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				CacheService
						.save(DoService.login(username, password1, "false"));
				CacheService.saveProfile(CpService.profile());
				DataService.setStruMap(DoService.xiaoquStru());
				DataService.setGroupList(SpaceService.group());
			//	DataService.setTagList(SpaceService.tagList()); //获取分类接口
				if (!DataService.isHavingTag()) {
					DataService.setTagList(SpaceService.tagList());
				}
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				CacheService.setLogin(username, password1);
				Intent intent = new Intent(context, IndexActivity.class);
			//	intent.putExtra("beginToload", true);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				
				if (LoginMapActivity.activity != null) {
					LoginMapActivity.activity.finish();		
				}
				if (RegFirstActivity.activity != null) {
					RegFirstActivity.activity.finish();
				}
				if (RegSecondActivity.activity != null) {
					RegSecondActivity.activity.finish();
				}
				finish();
					
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}
		
	/**
	 * 处理操作结果
	 * <p>
	 * 如果获取到用户的名称，则显示名称；否则如果已经授权，则显示
	 *平台名称
	 */
	public boolean handleMessage(Message msg) {
		Platform plat = (Platform) msg.obj;
		String text =actionToString(msg.arg2);
		switch (msg.arg1) {
			case 1: {
				// 成功
//				text = plat.getName() + " completed at " + text;
//				showMessage(text);
				task = new SinaLoginTask().execute();
			}
			break;			
			case 2: {
				// 成功
//				text = plat.getName() + " completed at " + text;
//				showMessage(text);
				task = new TencentLoginTask().execute();
			}
			break;		
			case 3: {
				// 取消
				text = plat.getName() + " canceled at " + text;
			//	Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
				showMessage(text);
				return false;
			}
			case 4: {
				// 失败
				text = plat.getName() + " caught error at " + text;
				showMessage(text);
				return false;
			}
		}

	
		return false;
	}
	
	/** 将action转换为String */
	public  static String actionToString(int action) {
		switch (action) {
			case Platform.ACTION_AUTHORIZING: return "ACTION_AUTHORIZING";
			case Platform.ACTION_GETTING_FRIEND_LIST: return "ACTION_GETTING_FRIEND_LIST";
			case Platform.ACTION_FOLLOWING_USER: return "ACTION_FOLLOWING_USER";
			case Platform.ACTION_SENDING_DIRECT_MESSAGE: return "ACTION_SENDING_DIRECT_MESSAGE";
			case Platform.ACTION_TIMELINE: return "ACTION_TIMELINE";
			case Platform.ACTION_USER_INFOR: return "ACTION_USER_INFOR";
			case Platform.ACTION_SHARE: return "ACTION_SHARE";
			default: {
				return "UNKNOWN";
			}
		}
	}


}
